package com.hj.collegetravel.services.impl;

import com.hj.collegetravel.dao.*;
import com.hj.collegetravel.models.*;
import com.hj.collegetravel.services.IUserService;
import com.hj.collegetravel.tools.CookieUtils;
import com.hj.collegetravel.tools.DeleteFileUtil;
import com.hj.collegetravel.tools.GetIpAddr;
import com.ndktools.javamd5.Mademd5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	CUserMapper userMapper;
	@Autowired
	CSchoolMapper schoolMapper;
	@Autowired
	CViewMapper viewMapper;
	@Autowired
	CPictureMapper pictureMapper;
	@Autowired
	CCommentMapper commentMapper;
	@Autowired
	CIndexMapper indexMapper;
	@Autowired
	CUpdateMapper updateMapper;


	SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd");
	String pathPic = this.getClass().getResource("/").getPath() + "static/images/picture/";

	/**
	 * 主页
	 */
	@Override
	public void index(HttpServletRequest request) {
		//景点推荐-8个
		CViewExample cViewExample = new CViewExample();
		cViewExample.or().andVFlagNotEqualTo(0).andVFlagNotEqualTo(4);
		cViewExample.setOrderByClause("v_hot desc");
		List<CView> cViewList = viewMapper.selectByExample(cViewExample);
		int i = 0;
		for (CView cView : cViewList){
			if (i>7)
				break;
			CPictureExample cPictureExample = new CPictureExample();
			cPictureExample.or().andPFlagEqualTo(1).andPVsidEqualTo(cView.getvId());
			List<CPicture> pictureList = pictureMapper.selectByExample(cPictureExample);
			if (pictureList.size()!=0)
				cViewList.get(i).setvEat(pictureList.get(0).getpFilename());//将图片名暂存eat字段
			else
				cViewList.get(i).setvEat(null);
			i++;
		}
		//轮播图
		CIndexExample cIndexExample = new CIndexExample();
		cIndexExample.or().andIDisplayEqualTo(1);
		cIndexExample.setOrderByClause("i_index");
		List<CIndex> cIndexList = indexMapper.selectByExample(cIndexExample);

		request.setAttribute("cViewList",cViewList.subList(0,cViewList.size()<8?cViewList.size():8));
		request.setAttribute("cIndexList",cIndexList);
	}

	/**
	 * 检查邮箱是否被注册
	 */
	@Override
	public boolean checkEmail(String email){
		CUserExample userExample = new CUserExample();
		userExample.or().andUEmailEqualTo(email);
		return userMapper.selectByExample(userExample).size()>0;//已被注册：返回true
	}

	/**
	 * 检查用户名是否被注册
	 */
	@Override
	public boolean checkUsername(String username){
		CUserExample userExample = new CUserExample();
		userExample.or().andUNameEqualTo(username);
		return userMapper.selectByExample(userExample).size()>0;//已被注册：返回true
	}

	/**
	 * 注册·post
	 */
	@Override
	public boolean dosignup(CUser user) {
		Mademd5 mademd5 = new Mademd5();
		String password = mademd5.toMd5(user.getuPassword());
		user.setuPassword(password);
		user.setuRegtime(new Date());
		user.setuPic("user.png");//默认头像
		user.setuSex(3);//默认性别：保密
		return userMapper.insert(user)>0;
	}

	/**
	 * 登录·post
	 */
	@Override
	public boolean dologin(String login, String password, HttpServletRequest request, HttpServletResponse response, String remember) {
		if (remember==null)
			remember = "";
		Mademd5 mademd5 = new Mademd5();
		String pass = password;
		password = mademd5.toMd5(password);
		CUserExample example = new CUserExample();
		example.or().andUNameEqualTo(login).andUPasswordEqualTo(password);
		List<CUser> list1 = userMapper.selectByExample(example);

		if (list1.size()>0){//用户名登录
			CUser cUser = list1.get(0);
			cUser.setuLogintime(new Date());
			cUser.setuIp(GetIpAddr.getIpAddr(request));
			userMapper.updateByPrimaryKey(cUser);

			if (remember.equals("on")){
				CookieUtils.addCookie("login",login);
				CookieUtils.addCookie("pass",pass);
				CookieUtils.addCookie("remember","checked");
			}
			else{
				CookieUtils.removeCookie("login");
				CookieUtils.removeCookie("pass");
				CookieUtils.removeCookie("remember");
			}
			cUser.setuPassword("");
			CookieUtils.addCookie("user", cUser); //放入Session

			return true;
		}
		else  {//邮箱登录
			example = new CUserExample();
			example.or().andUEmailEqualTo(login).andUPasswordEqualTo(password);
			List<CUser> list2 = userMapper.selectByExample(example);
			if (list2.size()>0){
				CUser cUser = list2.get(0);
				cUser.setuLogintime(new Date());
				cUser.setuIp(GetIpAddr.getIpAddr(request));
				userMapper.updateByPrimaryKey(cUser);

				if (remember.equals("on")){
					CookieUtils.addCookie("login",login);
					CookieUtils.addCookie("pass",pass);
					CookieUtils.addCookie("remember","checked");
				}
				else{
					CookieUtils.removeCookie("login");
					CookieUtils.removeCookie("pass");
					CookieUtils.removeCookie("remember");
				}
				cUser.setuPassword("");
				CookieUtils.addCookie("user", cUser); //放入Session
				return true;
			}
		}
		return false;
	}

	/**
	 * QQ登录
	 */
	@Override
	public boolean qqlogin(String openid, HttpServletRequest request, HttpServletResponse response) {
		CUserExample cUserExample = new CUserExample();
		cUserExample.or().andUQqidEqualTo(openid);
		List<CUser> cUserList = userMapper.selectByExample(cUserExample);
		if (cUserList.size()>0){
			CUser cUser = cUserList.get(0);
			cUser.setuLogintime(new Date());
			cUser.setuIp(GetIpAddr.getIpAddr(request));
			userMapper.updateByPrimaryKey(cUser);

			cUser.setuPassword("");
			CookieUtils.addCookie("user", cUser); //放入Session
			return true;
		}
		else {
			CUser cUser = new CUser();
			cUser.setuQqid(openid);
			cUser.setuPic("user.png");
			cUser.setuPassword(System.currentTimeMillis()+"");
			cUser.setuName("QQ用户_"+String.valueOf(System.currentTimeMillis()).substring(8));
			cUser.setuSex(3);
			cUser.setuEmail("");
			cUser.setuRegtime(new Date());
			cUser.setuLogintime(new Date());
			cUser.setuIp(GetIpAddr.getIpAddr(request));
			userMapper.insert(cUser);
			cUserExample = new CUserExample();
			cUserExample.or().andUQqidEqualTo(openid);
			cUserList = userMapper.selectByExample(cUserExample);
			if (cUserList.size()>0) {
				cUser = cUserList.get(0);
				cUser.setuPassword("");
				CookieUtils.addCookie("user", cUser); //放入Session
				return true;
			}
			return false;
		}
	}

	/**
	 * 找回密码·post
	 */
	@Override
	public boolean forget(CUser user, HttpServletRequest request) {
		Mademd5 mademd5 = new Mademd5();
		String email = request.getSession().getAttribute("useremail").toString();
		String password = mademd5.toMd5(user.getuPassword());
		CUserExample cUserExample = new CUserExample();
		cUserExample.or().andUEmailEqualTo(email);
		CUser user1 = userMapper.selectByExample(cUserExample).get(0);
		user1.setuPassword(password);
		return userMapper.updateByPrimaryKey(user1)>0;
	}

	/**
	 * 我的
	 */
	@Override
	public void person(HttpServletRequest request) {
		CUser user = CookieUtils.getCookie("user",CUser.class);
		if (user!=null) {
			user = userMapper.selectByPrimaryKey(user.getuId());
			if (user!=null)
				user.setuPassword("");
		}
		request.setAttribute("user",user);
	}

	/**
	 * 大学
	 * @param sId 学校id
	 */
	@Override
	public void college(Integer sId, HttpServletRequest request) {
		sId = sId==null?1:sId;
		CSchool cSchool = schoolMapper.selectByPrimaryKey(sId);
		request.setAttribute("school",cSchool);
	}

	/**
	 * 学校简介
	 */
	@Override
	public void college_introduce(Integer sId, HttpServletRequest request) {
		sId = sId==null?1:sId;
		CSchool cSchool = schoolMapper.selectByPrimaryKey(sId);
		request.setAttribute("school",cSchool);
	}

	/**
	 * 地理位置
	 */
	@Override
	public void college_position(Integer sId, HttpServletRequest request) {
		sId = sId==null?1:sId;
		CSchool cSchool = schoolMapper.selectByPrimaryKey(sId);
		//学校地图
		CPictureExample cPictureExample = new CPictureExample();
		cPictureExample.or().andPVsidEqualTo(sId).andPFlagEqualTo(2);
		List<CPicture> cPictureList = pictureMapper.selectByExample(cPictureExample);
		request.setAttribute("school",cSchool);
		request.setAttribute("cPictureList",cPictureList);
	}

	/**
	 * 校内景点
	 */
	@Override
	public void college_in(Integer sId, HttpServletRequest request) {
		sId = sId==null?1:sId;
		CSchool cSchool = schoolMapper.selectByPrimaryKey(sId);
		//校内景点
		CViewExample cViewExample = new CViewExample();
		cViewExample.or().andVSidEqualTo(sId).andVFlagEqualTo(0);
		List<CView> cViewList = viewMapper.selectByExample(cViewExample);
		//景点图片
		List<List<CPicture>> cPictureList = new ArrayList<>();
		CPictureExample cPictureExample = new CPictureExample();
		for (CView cView : cViewList) {
			cPictureExample.clear();
			cPictureExample.or().andPVsidEqualTo(cView.getvId()).andPFlagEqualTo(1);
			List<CPicture> PictureList = pictureMapper.selectByExample(cPictureExample);
			cPictureList.add(PictureList);
		}
		request.setAttribute("school",cSchool);
		request.setAttribute("cViewList",cViewList);
		request.setAttribute("cPictureList",cPictureList);
	}

	/**
	 * 周边景点
	 */
	@Override
	public void college_out(Integer sId, HttpServletRequest request) {
		sId = sId==null?1:sId;
		CSchool cSchool = schoolMapper.selectByPrimaryKey(sId);
		//周边景点
		CViewExample cViewExample = new CViewExample();
		cViewExample.or().andVSidEqualTo(sId).andVFlagNotEqualTo(0).andVFlagNotEqualTo(4);
		List<CView> cViewList = viewMapper.selectByExample(cViewExample);
		//景点图片
		List<List<CPicture>> cPictureList = new ArrayList<>();
		CPictureExample cPictureExample = new CPictureExample();
		for (CView cView : cViewList) {
			cPictureExample.clear();
			cPictureExample.or().andPVsidEqualTo(cView.getvId()).andPFlagEqualTo(1);
			List<CPicture> PictureList = pictureMapper.selectByExample(cPictureExample);
			cPictureList.add(PictureList);
		}
		request.setAttribute("school",cSchool);
		request.setAttribute("cViewList",cViewList);
		request.setAttribute("cPictureList",cPictureList);
	}

	/**
	 * 景点详情
	 */
	@Override
	public void detail(Integer vId, HttpServletRequest request) {
		CView cView = viewMapper.selectByPrimaryKey(vId);
		//景点图片
		CPictureExample cPictureExample = new CPictureExample();
		cPictureExample.or().andPVsidEqualTo(vId).andPFlagEqualTo(1);
		List<CPicture> cPictureList = pictureMapper.selectByExample(cPictureExample);
		//评论
		CCommentExample cCommentExample = new CCommentExample();
		cCommentExample.or().andCVidEqualTo(vId).andCFlagEqualTo(0);
		cCommentExample.setOrderByClause("c_id desc");
		List<CComment> cCommentList = commentMapper.selectByExampleWithBLOBs(cCommentExample);
		int i = 0;
		List commentPic = new ArrayList();
		for (CComment cComment : cCommentList){
			CUser cUser = userMapper.selectByPrimaryKey(cComment.getcUid());
			cCommentList.get(i).setUicon(cUser.getuPic());
			cCommentList.get(i).setUname(cUser.getuName());
			cCommentList.get(i).setTime(df1.format(cComment.getcTime()));
			//评论条数
			CCommentExample cCommentExample1 = new CCommentExample();
			cCommentExample1.or().andCCidEqualTo(cComment.getcId()).andCFlagNotEqualTo(0);
			int a = commentMapper.selectByExample(cCommentExample1).size();
			cCommentList.get(i).setcRead(a);//暂存已读字段

			//评论图片
			CPictureExample cPictureExample1 = new CPictureExample();
			cPictureExample1.or().andPFlagEqualTo(3).andPVsidEqualTo(cComment.getcId());
			List<CPicture> cPictureList1 = pictureMapper.selectByExample(cPictureExample1);
			commentPic.add(cPictureList1);
			i++;
		}
		//用户
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		request.setAttribute("cView",cView);
		request.setAttribute("user",cUser);
		request.setAttribute("cCommentList",cCommentList);
		request.setAttribute("cPictureList",cPictureList);
		request.setAttribute("commentPic",commentPic);
	}

	/**
	 * 用户中心
	 */
	@Override
	public void person_center(Integer uId, HttpServletRequest request) {
		CUser cUser = userMapper.selectByPrimaryKey(uId);
		if (cUser!=null){
			cUser.setuPassword("");
			if (cUser.getuEmail()!=null)
				cUser.setuEmail(cUser.getuEmail().replaceAll("(\\w?)(\\w+)(\\w)(@\\w+\\.[a-z]+(\\.[a-z]+)?)", "$1****$3$4"));
			if (cUser.getuTel()!=null)
				cUser.setuTel(cUser.getuTel().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
		}
		request.setAttribute("user",cUser);
	}

	/**
	 * 提交评论
	 */
	@Override
	public boolean sendComment(String content, Integer vId, String[] imgArr, HttpServletRequest request) {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		if (cUser!=null) {
			Date date = new Date();
			//添加评论
			CComment cComment = new CComment();
			cComment.setcTime(date);
			cComment.setcContent(content);
			cComment.setcVid(vId);
			cComment.setcUid(cUser.getuId());
			cComment.setcFlag(0);
			cComment.setcRead(1);
			commentMapper.insert(cComment);

			//获取评论
			CCommentExample cCommentExample = new CCommentExample();
			cCommentExample.or().andCFlagEqualTo(0).andCVidEqualTo(vId).andCUidEqualTo(cUser.getuId()).andCTimeEqualTo(date);
			List<CComment> cCommentList = commentMapper.selectByExample(cCommentExample);
			if (cCommentList.size()==0)
				return false;
			CComment cComment1 = cCommentList.get(0);

			CPicture cPicture = new CPicture();
			cPicture.setpFlag(3);
			cPicture.setpTime(date);
			//上传图片
			if (imgArr.length==1&&imgArr[0].equals("a"))
				return true;
			int flag = 0;//正常情况-多图
			if (imgArr.length==2&&imgArr[0].length()<30){
				flag = 1;//单图
			}
			for (String file : imgArr) {
				Base64.Decoder decoder = Base64.getDecoder();
				// 去掉base64编码的头部 如："data:image/jpeg;base64," 如果不去，转换的图片不可以查看
				String suffix = file.substring(file.indexOf("/",0)+1,(file.indexOf(";",0)));
				if (flag==1)
					file = imgArr[1];
				file = file.replace("data:image/jpeg;base64,","").replace("data:image/png;base64,","");
				//解码
				byte[] imgByte = decoder.decode(file);
				String iconPath = this.getClass().getResource("/").getPath() + "static/images/picture/";//图片目录
				String fileName = "CommentPicture_" + vId + "_"+cUser.getuId()+"_"+System.currentTimeMillis()+"."+suffix;//图片名

				try {
					FileOutputStream out = new FileOutputStream(iconPath + fileName); // 输出文件路径
					out.write(imgByte);
					out.close();

					//图片表
					cPicture.setpFilename(fileName);
					cPicture.setpVsid(cComment1.getcId());
					pictureMapper.insert(cPicture);

				} catch (Exception e) {
					e.printStackTrace();
				}
				if (flag==1)
					break;
			}
			return true;
		}
		return false;
	}

	/**
	 * 回复评论
	 */
	@Override
	public boolean sendComment2(String content, Integer vId, Integer cId, Integer uId, HttpServletRequest request) {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		if (cUser!=null) {
			CComment cComment = new CComment();
			cComment.setcTime(new Date());
			cComment.setcContent(content);
			cComment.setcVid(vId);
			cComment.setcUid(cUser.getuId());
			cComment.setcFlag(uId);
			cComment.setcCid(cId);
			cComment.setcRead(0);
			return commentMapper.insert(cComment)>0;
		}
		return false;
	}

	/**
	 * 景点列表 1.名胜古迹 2.城市公园 3.游山玩水 4.酒店住宿
	 */
	@Override
	public void view(Integer num, Integer sId,HttpServletRequest request) {
		if (num == null)
			num = 1;
		if (sId == null)
			sId = 1;
		CViewExample cViewExample = new CViewExample();
		cViewExample.or().andVFlagEqualTo(num).andVSidEqualTo(sId);
		cViewExample.setOrderByClause("v_hot desc");
		List<CView> cViewList = viewMapper.selectByExampleWithBLOBs(cViewExample);
		int i = 0;
		for (CView cView : cViewList){
			CPictureExample cPictureExample = new CPictureExample();
			cPictureExample.or().andPFlagEqualTo(1).andPVsidEqualTo(cView.getvId());
			cViewList.get(i).setvEat(pictureMapper.selectByExample(cPictureExample).get(0).getpFilename());//将图片名暂存eat字段
			i++;
		}
		String str = "-";
		if (num.equals(1))
			str = "名胜古迹";
		else if (num.equals(2))
			str = "城市公园";
		else if (num.equals(3))
			str = "游山玩水";
		else if (num.equals(4))
			str = "酒店住宿";
		//学校列表
		CSchoolExample cSchoolExample = new CSchoolExample();
		List<CSchool> cSchoolList = schoolMapper.selectByExample(cSchoolExample);

		request.setAttribute("cViewList",cViewList);
		request.setAttribute("str",str);
		request.setAttribute("sId",sId);
		request.setAttribute("num",num);
		request.setAttribute("cSchoolList",cSchoolList);
	}

	/**
	 * 搜索·get
	 */
	@Override
	public void search(HttpServletRequest request) {
		//热门搜索 - 12个
		CViewExample cViewExample = new CViewExample();
		cViewExample.setOrderByClause("v_hot desc");
		List<CView> cViewList = viewMapper.selectByExample(cViewExample);
		//搜索历史
		String search = CookieUtils.getCookie("search");
		List<String> searchList = null;
		if (search!=null) {
			searchList = Arrays.asList(search.split("#"));
		}

		request.setAttribute("cViewList",cViewList.subList(0,cViewList.size()<12?cViewList.size():12));
		request.setAttribute("searchList",searchList==null?searchList:searchList.subList(0,searchList.size()<20?searchList.size():20));

	}

	/**
	 * 搜索结果
	 */
	@Override
	public void searchResult(String s, HttpServletRequest request) {
		if (s==null||s.equals("")) {
			request.setAttribute("cViewList", null);
			return;
		}
		//搜索历史
		String  history = CookieUtils.getCookie("search");
		if (history!=null) {
			history = "#" + history +"#";
			history = history.replace("#"+s+"#","#");
			history = s + history.substring(0,history.length()-1);
		}
		else
			history = s;
		CookieUtils.removeCookie("search");
		CookieUtils.addCookie("search",history);
		//搜索结果
		CViewExample cViewExample = new CViewExample();
		cViewExample.setOrderByClause("v_hot desc");
		cViewExample.or().andVNameLike("%"+s+"%");
		List<CView> cViewList = viewMapper.selectByExample(cViewExample);
		int i = 0;
		for (CView cView : cViewList){
			CPictureExample cPictureExample = new CPictureExample();
			cPictureExample.or().andPFlagEqualTo(1).andPVsidEqualTo(cView.getvId());
			cViewList.get(i).setvEat(pictureMapper.selectByExample(cPictureExample).get(0).getpFilename());//将图片名暂存eat字段
			i++;
		}

		request.setAttribute("cViewList", cViewList);
		request.setAttribute("s", s);
	}

	/**
	 * 发现
	 */
	@Override
	public void find(HttpServletRequest request) {
		//景点
		CViewExample cViewExample = new CViewExample();
		cViewExample.or().andVFlagNotEqualTo(0).andVFlagNotEqualTo(4);
		cViewExample.setOrderByClause("v_id desc");
		List<CView> cViewList = viewMapper.selectByExample(cViewExample);
		int i = 0;
		for (CView cView : cViewList){
			CPictureExample cPictureExample = new CPictureExample();
			cPictureExample.or().andPFlagEqualTo(1).andPVsidEqualTo(cView.getvId());
			cViewList.get(i).setvEat(pictureMapper.selectByExample(cPictureExample).get(0).getpFilename());//将图片名暂存eat字段
			i++;
		}
		request.setAttribute("cViewList", cViewList);
	}

	/**
	 * 我的评论
	 */
	@Override
	public void comment(HttpServletRequest request) {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		if (cUser==null) {
			request.setAttribute("cCommentList", null);
			return;
		}
		CCommentExample cCommentExample = new CCommentExample();
		cCommentExample.setOrderByClause("c_id desc");
		cCommentExample.or().andCUidEqualTo(cUser.getuId());
		List<CComment> cCommentList = commentMapper.selectByExampleWithBLOBs(cCommentExample);
		SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm");
		int i = 0;
		List commentPic = new ArrayList();
		for (CComment cComment : cCommentList){
			if (i>20)
				break;
			String flag = "<span style='color:red;'>[回复]</span> ";
			if (cComment.getcFlag().equals(0))
				flag = "";
			cCommentList.get(i).setcContent(flag+cComment.getcContent());
			cCommentList.get(i).setTime(df.format(cComment.getcTime()));
			CView cView = viewMapper.selectByPrimaryKey(cComment.getcVid());
			if (cView!=null) {
				cCommentList.get(i).setUname(cView.getvName());
			}
			//评论图片
			CPictureExample cPictureExample1 = new CPictureExample();
			cPictureExample1.or().andPFlagEqualTo(3).andPVsidEqualTo(cComment.getcId());
			List<CPicture> cPictureList1 = pictureMapper.selectByExample(cPictureExample1);
			commentPic.add(cPictureList1);
			i++;
		}

		request.setAttribute("cCommentList",cCommentList.subList(0,cCommentList.size()<20?cCommentList.size():20));
		request.setAttribute("commentPic",commentPic);
	}

	/**
	 * 删除评论
	 */
	@Override
	public boolean delComment(Integer cId, HttpServletRequest request) {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		if (cUser!=null) {
			CComment cComment = commentMapper.selectByPrimaryKey(cId);
			if (cComment!=null){
				if (cComment.getcUid().equals(cUser.getuId())) {
					List<Integer> cIdList = new ArrayList<>();
					cIdList.add(cComment.getcId());
					//获取子评论
					CCommentExample cCommentExample = new CCommentExample();
					cCommentExample.or().andCFlagNotEqualTo(0).andCCidEqualTo(cComment.getcId());
					List<CComment> cCommentList = commentMapper.selectByExample(cCommentExample);
					for (CComment cComment1 : cCommentList){
						cIdList.add(cComment1.getcId());
					}
					//删除评论图片
					CPictureExample cPictureExample = new CPictureExample();
					cPictureExample.or().andPFlagEqualTo(3).andPVsidIn(cIdList);
					List<CPicture> cPictureList = pictureMapper.selectByExample(cPictureExample);
					for (CPicture cPicture : cPictureList){
						//删除图片文件
						DeleteFileUtil.deleteFile(pathPic+cPicture.getpFilename());
						//删数据库
						pictureMapper.deleteByPrimaryKey(cPicture.getpId());
					}
					//删除子评论
					commentMapper.deleteByExample(cCommentExample);
					//删除评论
					return commentMapper.deleteByPrimaryKey(cId)>0;
				}
			}
		}
		return false;
	}

	/**
	 * 加载评论
	 */
	@Override
	public void getComment(Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		if (cUser!=null) {
			CCommentExample cCommentExample = new CCommentExample();
			cCommentExample.setOrderByClause("c_id desc");
			cCommentExample.or().andCUidEqualTo(cUser.getuId()).andCIdLessThan(id);
			List<CComment> cCommentList = commentMapper.selectByExampleWithBLOBs(cCommentExample);
			SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm");
			int i = 0;
			String s = "";
			int mid = 0;
			for (CComment cComment : cCommentList){
				if (i>=15)
					break;
				String flag = "<span style='color:red;'>[回复]</span> ";
				if (cComment.getcFlag().equals(0))
					flag = "";
				CView cView = viewMapper.selectByPrimaryKey(cComment.getcVid());
				if (cView!=null) {
					mid = cComment.getcId();
					//评论图片
					CPictureExample cPictureExample1 = new CPictureExample();
					cPictureExample1.or().andPFlagEqualTo(3).andPVsidEqualTo(cComment.getcId());
					List<CPicture> cPictureList1 = pictureMapper.selectByExample(cPictureExample1);
					String pic = "";
					for (CPicture cPicture : cPictureList1){
						pic += "                    <li>\n" +
								"                        <div class=\"am-gallery-item\">\n" +
								"                            <img src=\"images/picture/"+cPicture.getpFilename()+"\"/>\n" +
								"                        </div>\n" +
								"                    </li>\n";
					}
					s += "<a href=\"javascript:;\" class=\"aui-assets-item comment"+cComment.getcId()+"\">\n" +
							"            <div class=\"aui-assets-day\">\n" +
							"                <i class=\"icon icon-time\"></i>"+df.format(cComment.getcTime())+"\n" +
							"            </div>\n" +
							"            <div class=\"aui-assets-box\">\n" +
							"                <h2><span onclick=\"javascript:location.href='detail?vId="+cComment.getcVid()+"'\" style=\"color: #03A9F4;\">#"+cView.getvName()+"#</span> <span class=\"del\" onclick=\"dodel("+cComment.getcId()+")\">删除</span></h2>\n" +
							"                <div class=\"aui-flex\" onclick=\"javascript:location.href='detail?vId="+cComment.getcVid()+"'\">\n" +
							"                    <div class=\"aui-flex-box\">\n" +
							"                        <p>"+flag+cComment.getcContent()+"</p>\n" +
							"                    </div>\n" +
							"                </div>\n" +
							"<ul data-am-widget=\"gallery\" class=\"am-gallery am-avg-sm-3 am-avg-md-3 am-avg-lg-4 am-gallery-default\" style=\"margin-left: -10px;\" data-am-gallery=\"{ pureview: true }\" >"+
							 pic+
							"                </ul>"+
							"            </div>\n" +
							"        </a>";

				}
				i++;
			}
			if (cCommentList.size()==0){
				response.getWriter().write("{\"status\":0,\"tips\":\"没有更多内容了~\"}");
				return;
			}
			String tips = "加载更多";
			if (cCommentList.size()<=15)
				tips = "没有更多内容了~";
			s = s.replace("\"","\\\"").replace("\n","");
			response.getWriter().write("{\"status\":1,\"tips\":\""+tips+"\",\"s\":\""+s+"\",\"id\":\""+mid+"\"}");
		}
		else
			response.getWriter().write("{\"status\":-1,\"tips\":\"请先登录。\"}");
	}

	/**
	 * 评论详情
	 */
	@Override
	public void comment_detail(Integer cId, HttpServletRequest request) {
		CCommentExample cCommentExample = new CCommentExample();
		cCommentExample.or().andCCidEqualTo(cId);
		cCommentExample.setOrderByClause("c_id desc");
		List<CComment> cCommentList = commentMapper.selectByExampleWithBLOBs(cCommentExample);
		int i = 0;
		for (CComment cComment : cCommentList){
			CUser cUser = userMapper.selectByPrimaryKey(cComment.getcUid());
			cCommentList.get(i).setUicon(cUser.getuPic());
			cCommentList.get(i).setUname(cUser.getuName());
			cCommentList.get(i).setTime(df1.format(cComment.getcTime()));
			if (cComment.getcFlag()>100) {
				cUser = userMapper.selectByPrimaryKey(cComment.getcFlag());
				cCommentList.get(i).setUicon2(cUser.getuPic());
				cCommentList.get(i).setUname2(cUser.getuName());
			}
			i++;
		}

		CComment cComment = commentMapper.selectByPrimaryKey(cId);
		if (cComment!=null){
			cComment.setTime(new SimpleDateFormat("MM-dd HH:mm").format(cComment.getcTime()));
			CUser cUser = userMapper.selectByPrimaryKey(cComment.getcUid());
			cComment.setUicon(cUser.getuPic());
			cComment.setUname(cUser.getuName());
		}
		//评论图片
		CPictureExample cPictureExample1 = new CPictureExample();
		cPictureExample1.or().andPFlagEqualTo(3).andPVsidEqualTo(cId);
		List<CPicture> cPictureList = pictureMapper.selectByExample(cPictureExample1);

		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		request.setAttribute("cPictureList",cPictureList);
		request.setAttribute("cCommentList",cCommentList);
		request.setAttribute("cComment",cComment);
		request.setAttribute("user",cUser);
	}

	/**
	 * 修改资料·get
	 */
	@Override
	public void modify(HttpServletRequest request) {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		cUser = userMapper.selectByPrimaryKey(cUser.getuId());
		request.setAttribute("user",cUser);
	}

	/**
	 * 修改资料·post
	 */
	@Override
	public boolean domodify(CUser cUser1, HttpServletRequest request) {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		cUser = userMapper.selectByPrimaryKey(cUser.getuId());
		cUser.setuName(cUser1.getuName());
		cUser.setuTel(cUser1.getuTel());
		cUser.setuSex(cUser1.getuSex());
		cUser.setuIntroduction(cUser1.getuIntroduction());
		return userMapper.updateByPrimaryKeySelective(cUser)>0;
	}

	/**
	 * 更换邮箱·post
	 */
	@Override
	public Integer do_modify_email(String password, HttpServletRequest request) {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		cUser = userMapper.selectByPrimaryKey(cUser.getuId());
		Mademd5 mademd5 = new Mademd5();
		String email = request.getSession().getAttribute("useremail").toString();
		password = mademd5.toMd5(password);
		if (cUser.getuPassword().equals(password)){
			cUser.setuEmail(email);
			return userMapper.updateByPrimaryKeySelective(cUser);
		}
		return -1;
	}

	/**
	 * 修改密码
	 */
	@Override
	public Integer do_modify_pass(String pass1, String pass2, HttpServletRequest request) {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		cUser = userMapper.selectByPrimaryKey(cUser.getuId());
		Mademd5 mademd5 = new Mademd5();
		pass1 = mademd5.toMd5(pass1);
		pass2 = mademd5.toMd5(pass2);
		if (cUser.getuPassword().equals(pass1)){
			cUser.setuPassword(pass2);
			return userMapper.updateByPrimaryKeySelective(cUser);
		}
		return -1;
	}

	/**
	 * 更换头像·post
	 */
	@Override
	public boolean doheadicon(String file, HttpServletRequest request) {
		CUser cUser = CookieUtils.getCookie("user",CUser.class);
		cUser = userMapper.selectByPrimaryKey(cUser.getuId());
		Base64.Decoder decoder = Base64.getDecoder();
		// 去掉base64编码的头部 如："data:image/jpeg;base64," 如果不去，转换的图片不可以查看
		String suffix = file.substring(file.indexOf("/",0)+1,(file.indexOf(";",0)));
		file = file.replace("data:image/jpeg;base64,","").replace("data:image/png;base64,","");
		//解码
		byte[] imgByte = decoder.decode(file);
		String iconPath = this.getClass().getResource("/").getPath() + "static/images/headicon/";//图片目录
		String fileName = "UserIcon_"+cUser.getuId()+"_"+System.currentTimeMillis()+"."+suffix;//图片名

		try {
			FileOutputStream out = new FileOutputStream(iconPath + fileName); // 输出文件路径
			out.write(imgByte);
			out.close();

			//删除头像文件
			if (!cUser.getuPic().equals("user.png")){
				DeleteFileUtil.deleteFile(iconPath + cUser.getuPic());
			}
			else{
				System.out.println("-------==默认头像，不删除==---------");
			}

			//更换头像
			cUser.setuPic(fileName);
			userMapper.updateByPrimaryKeySelective(cUser);
			return true;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 检查更新
	 */
	@Override
	public CUpdate checkUpdate(String version, HttpServletRequest request) {
		CUpdateExample updateExample = new CUpdateExample();
		updateExample.setOrderByClause("u_id desc");
		List<CUpdate> updateList = updateMapper.selectByExample(updateExample);
		CUpdate update = new CUpdate();
		if (updateList.size()>0&&!updateList.get(0).getuVersion().equals(version))
			update = updateList.get(0);
		else
			update.setuId(0);//无更新
		return update;
	}
}
